import {Res, ResPage} from "@/api/objects";
import REQ from "@/api/web/REQ.ts";

export interface FileObj {
    name: string,
    type: string,
    contentType: string,
    path: string,
    dir: boolean,
    lastUpdateTime: number,
    size: number,
    hidden: boolean
}

export interface getByPathParam {
    // 文件夹路径
    path: string
    // 分页大小
    pageSize: number
    // 当前页码
    pageCurrent: number
}

class FileApi {

    dirByPath = (path: string, current: number, size: number): {
        res: Promise<Res<ResPage<FileObj>>>,
        abort: () => void
    } => {
        const abortDirByPath = new AbortController()
        const res = REQ<any, Res<ResPage<FileObj>>>({
            method: 'get',
            params: {path, current, size},
            url: '/api/file/dir',
            signal: abortDirByPath.signal,
        })
        return {
            res,
            abort: () => {
                abortDirByPath.abort()
            },
        }
    }

    getFileObjByPath = async (path: string): Promise<Res<FileObj>> => {
        return await REQ<{ path: string }, Res<FileObj>>({
            method: 'get',
            params: {path},
            url: "/api/file/info",
        })
    }

    /**
     * 从文件对象中获取文件路径（用于类似img标签的src）
     * @param path 文件路径
     */
    getFileLink = (path: string) => {
        path = encodeURIComponent(path)
        return "/api/file?path=" + path
    }

    /**
     * 获取图片链接
     * @param path 文件路径
     * @param maxWidth 图片最大宽度（要求服务端对图片进行压缩）
     */
    getImageLink = (path: string, maxWidth?: number) => {
        path = encodeURIComponent(path)
        let p = "/api/img?path=" + path;
        if (maxWidth) {
            p += "&maxWidth=" + maxWidth
        }
        return p
    }

    /**
     * 获取获取m3u8文件的链接😁
     * @param path ts文件路径
     */
    getM3U8Link = (path: string) => {
        path = encodeURIComponent(path)
        return "/api/file/m3u8?path=" + path
    }

    /**
     * 以流的方式读取文件
     * @param path 请求路径
     * @param onLoad 获取到文件时，触发读取方法
     * @return function 终止请求
     */
    getFileAsString = (path: string, onLoad: (value: string) => void) => {
        const response = fetch(this.getFileLink(path), {
            method: "get",
        })

        let close = false

        response.then(res => {
            if (!res.ok) {
                throw new Error(`HTTP error! status: ${res.status}`);
            }
            if (res.body == null) {
                throw new Error('请求数据为空')
            }

            const reader = res.body.getReader();

            function push() {
                reader.read().then(({done, value}) => {
                    if (close) {
                        reader.cancel().then()
                        return
                    }

                    if (done) {
                        reader.cancel().then()
                        return
                    }

                    onLoad(new TextDecoder().decode(value))
                    push(); // 继续读取
                });
            }

            push();
        })
        return () => {
            close = true
        }
    }
}

export default new FileApi()
